import { CanActivate, ExecutionContext, ForbiddenException, Injectable } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { JwtService } from '@nestjs/jwt';
import { isArray } from 'class-validator';
import { FastifyRequest } from 'fastify';
import { Observable } from 'rxjs';

@Injectable()
export class PermissionGuard implements CanActivate {
  constructor(
    private readonly reflector: Reflector,
    private readonly jwtService: JwtService,
  ) { }
  canActivate(
    context: ExecutionContext,
  ): boolean | Promise<boolean> | Observable<boolean> {
    const request: FastifyRequest = context.switchToHttp().getRequest();
    const requiredPermissions = this.reflector.getAllAndOverride('require-permission', [
      context.getClass(),
      context.getHandler()
    ]);
    if (!requiredPermissions || !isArray(requiredPermissions) || requiredPermissions.length < 1) return true;

    const authorization = request.headers.authorization;

    if (authorization) {
      // 在token中获取用户权限,简单做法,实际项目中需要根据用户id查询用户权限
      const userPermissions = this.jwtService.verify(authorization)?.permissions;
      if (userPermissions && isArray(userPermissions) && userPermissions.length > 0) {
        if (requiredPermissions.every(item => userPermissions.includes(item))) {
          return true
        } else {
          throw new ForbiddenException("用户没有权限")
        }
      } else {
        throw new ForbiddenException("用户没有权限")
      }
    } else {
      throw new ForbiddenException("用户没有权限")
    }
  }
}
